/**
 * created by 小卷毛, 2020-07-29 029
 * Copyright (c) 2020, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.zhiyou.aifeng.common_ui.utils

import android.content.Context
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.tabs.TabLayout
import com.zhiyou.aifeng.common.base.find
import com.zhiyou.aifeng.common.base.getColorEx
import com.zhiyou.aifeng.common.base.inflate
import com.zhiyou.aifeng.common.base.oneClick
import com.zhiyou.aifeng.common_ui.R
import com.zhiyou.aifeng.common_ui.base.addItems
import com.zhiyou.aifeng.common_ui.model.AreaData
import net.idik.lib.slimadapter.SlimAdapter
import org.jetbrains.anko.design.listeners.onTabSelectedListener
import org.jetbrains.anko.toast

/**
 * 省、市、区、乡、村选择器
 * @param title     标题
 * @param items     显示数据
 * @param onResult  结果回调
 */
fun Context.showAreaDialog(
    title: String = "请选择所在地区",
    items: List<AreaData> = ArrayList(),
    onResult: (ArrayList<String>, String) -> Unit = { _, _ -> }
) {
    val dialog = BottomSheetDialog(this, R.style.BottomSheetDialogStyle)
    val view = inflate<View>(R.layout.dialog_area_hint)
    val mTab = view.find<TabLayout>(R.id.area_tab)
    val mRecycler = view.find<RecyclerView>(R.id.area_list)

    var mSelectIndex = 0
    val mList = ArrayList<AreaData>()

    view.find<TextView>(R.id.area_title).text = title
    view.find<TextView>(R.id.area_cancle).oneClick { dialog.dismiss() }
    view.find<TextView>(R.id.area_ok).oneClick {
        if (mList.none { it.isChecked }
            || mList.first { it.isChecked }.subList.isNotEmpty()
        ) {
            toast("请选择详细的地区信息！")
            return@oneClick
        }

        val ids = ArrayList<String>()
        val names = ArrayList<String>()
        val selectItems = ArrayList<AreaData>()

        selectItems.addItems(items)
        do {
            selectItems.first { it.isChecked }.apply {
                ids.add(this.id)
                names.add(this.name)

                selectItems.clear()
                if (this.subList.isNotEmpty()) {
                    selectItems.addItems(this.subList)
                }
            }
        } while (selectItems.isNotEmpty())

        dialog.dismiss()

        onResult.invoke(ids, names.joinToString(" "))
    }

    mRecycler.apply {
        (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        layoutManager = LinearLayoutManager(this@showAreaDialog)
        adapter = SlimAdapter.create()
            .register<AreaData>(R.layout.item_area_list) { data, injector ->
                injector.text(R.id.item_area_title, data.name)
                    .textColor(
                        R.id.item_area_title,
                        if (data.isChecked) getColorEx(R.color.colorAccent) else getColorEx(R.color.black)
                    )
                    .clicked(R.id.item_area) {
                        mTab.getTabAt(mSelectIndex)?.text = data.name
                        mList.filter { it.isChecked }.forEach { it.isChecked = false }
                        data.isChecked = true
                        (mRecycler.adapter as SlimAdapter).notifyDataSetChanged()

                        if (data.subList.isNotEmpty()) {
                            data.subList.forEach { it.isChecked = false }
                            mTab.apply {
                                val tab = newTab().setText("请选择")
                                addTab(tab)
                                postDelayed({ tab.select() }, 100)
                            }
                        }
                    }
            }
    }

    mTab.apply {
        onTabSelectedListener {
            onTabSelected { tab ->
                val position = tab!!.position
                if (position < mSelectIndex) {
                    for (index in mSelectIndex downTo (position + 1)) {
                        removeTabAt(index)
                    }
                }

                mSelectIndex = position

                mList.clear()
                mList.addItems(items)
                for (index in 1..mSelectIndex) {
                    if (mList.any { it.isChecked }) {
                        val inner = mList.first { it.isChecked }.subList
                        mList.clear()
                        mList.addItems(inner)
                    }
                }
                (mRecycler.adapter as SlimAdapter).updateData(mList)
                mRecycler.smoothScrollToPosition(0)
            }
        }

        addTab(newTab().setText("请选择"), true)
    }

    dialog.setContentView(view)
    dialog.show()
}